package com.durian.base.permission;

import android.content.Intent;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.durian.base.permission.listener.OnPermissionListener;
import com.durian.base.permission.task.IPermissionTask;
import com.durian.base.permission.xx.XXPermissions;

/**
 * 说明：SoonPermissionFragment
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019/6/3 18:16
 * <p/>
 * 版本：version 1.0
 */
public class PermissionFragment extends Fragment {

    private SoonPermission       mSoonPermission;
    private OnPermissionListener mCallback;
    private IPermissionTask      mTask;
    private boolean hasJump = false;
    private int mRequestCode;

    public PermissionFragment(){}

    public void setSoonPermission(SoonPermission soonPermission){
        mSoonPermission = soonPermission;
    }

    public void setTask(IPermissionTask task){
        mTask = task;
    }

    public void setCallback(OnPermissionListener callback){
        mCallback = callback;
    }

    public void startPermissionActivity(){
        mRequestCode = XXPermissions.startPermissionActivity(this, mTask.permissionGroup());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (hasJump){
            if (mRequestCode == requestCode){
                if (mTask.hasPermission(getActivity())){
                    mSoonPermission.execute();
                }else {
                    mSoonPermission.onDenied(mTask);
                }
            }
        }
        hasJump = true;
    }

    private void removeSoonPermissionFragment() {
        getFragmentManager().beginTransaction().remove(this).commitAllowingStateLoss();
    }
}
